#include "ConfigMgr.h"

ConfigMgr::ConfigMgr() {
  // 获取当前的工作目录
  boost::filesystem::path current_path = boost::filesystem::current_path();
  // 构建config.ini文件完整的路径
  boost::filesystem::path config_path = current_path / "config.ini";
  std::cout << "Config path: " << config_path << std::endl;

#ifdef LOG_DEBUG
  g_logs->info("配置文件路径:" + config_path.string());
#endif

  // 使用Boost.PropertyTree来读取INI文件
  boost::property_tree::ptree pt;

  try {
    boost::property_tree::read_ini(config_path.string(), pt);

    // 遍历ini配置文件中所有的section节点
    for (const auto& section_pair : pt) {
      // 节点名称
      const std::string& section_name = section_pair.first;
      const boost::property_tree::ptree& section_tree = section_pair.second;

      // 遍历每个section，遍历其所有的key-value键值对
      std::map<std::string, std::string> section_config;
      for (const auto& key_value_pair : section_tree) {
        const std::string& key = key_value_pair.first;
        const std::string& value =
            key_value_pair.second.get_value<std::string>();
        section_config[key] = value;
      }
      SectionInfo sectionInfo;
      sectionInfo._section_datas = section_config;

      // 将section的key-value对保存到config_map中
      _config_map[section_name] = sectionInfo;
    }
    // 输出所有的section和key-value对
    for (const auto& section_entry : _config_map) {
      const std::string& section_name = section_entry.first;
      SectionInfo section_config = section_entry.second;
      std::cout << "[" << section_name << "]" << std::endl;
      for (const auto& key_value_pair : section_config._section_datas) {
        std::cout << key_value_pair.first << "=" << key_value_pair.second
                  << std::endl;
      }
    }
#ifdef LOG_DEBUG
    g_logs->info("读取配置文件成功!");
#endif
  } catch (const std::exception& e) {
    std::cout << "读取配置文件失败 Error:" << e.what() << std::endl;
#ifdef LOG_DEBUG
    g_logs->info("读取配置文件失败。Error:{0}", e.what());
#endif
    // 延时 2 秒
    std::this_thread::sleep_for(std::chrono::seconds(3));
    exit(-1);
  }
}

//ConfigMgr::ConfigMgr(const ConfigMgr& src) {
//  this->_config_map = src._config_map;
//}
//
//ConfigMgr& ConfigMgr::operator=(const ConfigMgr& src) {
//  if (&src == this) {
//    return *this;
//  }
//
//  this->_config_map = src._config_map;
//}

SectionInfo ConfigMgr::operator[](const std::string& Section) {
  if (_config_map.find(Section) == _config_map.end()) {
    return SectionInfo();
  }

  return _config_map[Section];
}



ConfigMgr::~ConfigMgr() { _config_map.clear(); }
